package com.gztms.runner;

import com.gztms.blogmgnt.mapper.BlogMapper;
import com.gztms.blogmgnt.pojo.Blog;
import com.gztms.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Zoey
 * @date 2023/5/2 15:35
 * @Description 文章浏览量runner
 **/
@Component
public class ViewCountRunner implements CommandLineRunner {

    @Autowired
    private BlogMapper blogMapper;

    @Autowired
    private RedisCache redisCache;

    @Override
    public void run(String... args) throws Exception {
        // 1、查询博客信息 blogId, viewCount
        List<Blog> blogs = blogMapper.selectList(null);

        // 2、转换数据,  {id: xx ,viewCount:xx}
        Map<String, Integer> viewCountMap = blogs.stream()
                .collect(Collectors.toMap(blog -> blog.getBid().toString(),
                        blog -> blog.getViewCount().intValue()));

        // 2、存储到redis
        redisCache.setCacheMap("blog:viewCount",viewCountMap);

    }
}
